<?php
/**
 * Created by PhpStorm.
 * User: dy
 * Date: 2019/12/19
 * Time: 14:11
 */
namespace app\admin\controller;
use app\admin\model\AdminActionLogModel;
use app\admin\model\Recycle;
use app\admin\validate\AdminMenuValidate;
use app\common\controller\BackendController;
use app\admin\model\AdminMenu as AdminMenuModel;
use think\Exception;
use think\facade\Db;
use think\facade\View;

class AdminMenu extends BackendController
{
    /**
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index(){
        if($this->request->isAjax()){
            $this->model = AdminMenuModel::instance();
            list($where,$sort,$order,$page,$limit) = $this->model->buildParams($this->request);
            $total = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->with('ParentMenu')
                ->visible(['ParentMenu'=>['name']])
                ->append(['is_hide_text'])
                ->where($where)
                ->page($page,$limit)
                ->order('parent_id','ASC')
                ->order($sort,$order)
                ->select();
            $this->success('查询成功','',['list'=>$list,'total'=>$total]);
        }
        return view();
    }

    public function add(){
        if($this->request->isPost()){
            $data = $this->request->param('post');
            !isset($data['is_hide']) && $data['is_hide'] = 0;
            if(!AdminMenuValidate::instance()->scene('add')->check($data)){
                $this->error(AdminMenuValidate::instance()->getError());
            }
            $res = AdminMenuModel::create($data,['name','url','icon','sort','parent_id','is_hide','create_time']);
            if(!$res){
                $this->error('添加失败');
            }
            AdminActionLogModel::logAdd('添加菜单','菜单名称:'.$data['name']);
            $this->success('添加成功');
        }
        $select_view = $this->menu->menuToSelect($this->menuTree);
        View::assign('select_view',$select_view);
        return view('edit');
    }
    /**
     * @param null $id
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit($id = null){
        if($this->request->isPost()){
            $data = $this->request->param('post');
            !isset($data['is_hide']) && $data['is_hide'] = 0;
            if(!AdminMenuValidate::instance()->scene('edit')->check($data)){
                $this->error(AdminMenuValidate::instance()->getError());
            }
            $res = AdminMenuModel::update($data,[],['id','name','url','icon','sort','parent_id','is_hide','update_time']);
            if(!$res){
                $this->error('更新失败');
            }
            AdminActionLogModel::logAdd('更新菜单','菜单id:'.$data['id']);
            $this->success('更新成功');
        }
        if(!$id){
            $this->error('id不能为空!');
        }
        $menu_info = AdminMenuModel::find($id);
        $select_view = $this->menu->menuToSelect($this->menuTree);
        View::assign('info',$menu_info);
        View::assign('select_view',$select_view);
        return view();
    }
    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function delete(){
        $ids = $this->request->param('ids/a');
        if(empty($ids)){
            $this->error('删除的数据不能为空！');
        }
        $menu_list = AdminMenuModel::select($ids);
        $del_arr = [];
        foreach ($menu_list as $menu){
            $tmp = [
                'object_id'=>$menu['id'],
                'table_name'=>'admin_menu',
                'name'=>$menu['name'],
                'admin_id'=>$this->auth->id
            ];
            $del_arr[] = $tmp;
        }
        try {
            Db::transaction(function () use ($ids, $del_arr) {
                $res = AdminMenuModel::destroy($ids);
                if (!$res) {
                    throw new Exception('删除失败！', 401);
                }
                if (!Recycle::instance()->saveAll($del_arr)) {
                    throw new Exception('删除失败！', 402);
                }
            });
            AdminActionLogModel::logAdd('删除菜单','菜单ids:'.json_encode($ids));
            $this->success('删除成功');
        }catch (Exception $e){
            $this->error('删除失败');
        }
    }

    public function status(){
        $ids = $this->request->param('ids/a');
        $is_hide = $this->request->param('is_hide/d');
        if(empty($ids)){
            $this->error('更新的数据不能为空！');
        }
        $res = AdminMenuModel::update(['is_hide'=>$is_hide],[
            ['id','in',$ids]
        ],['is_hide']);
        if(!$res){
            $this->error('更新失败');
        }
        AdminActionLogModel::logAdd('菜单状态编辑','菜单ids:'.json_encode($ids).',is_hide:'.$is_hide);
        $this->success('更新成功');
    }
}